<template>
  <el-upload
    drag
    :action="action"
    :accept="fileType"
    :on-success="uploadSuccess"
    :on-progress="uploadProgress"
    :on-error="uploadError"
    :before-upload="beforeUpload"
    :on-remove="handleRemove"
    :limit="limit"
    :list-type="listType"
    :file-list="fileList"
    :data="data"
  >
    <template v-if="!fileLoding">
      <div
        v-if="fileList.length >= limit"
        :class="fileList.length >= limit ? 'disabled' : ''"
        @click.prevent="() => null"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">上传文件数量已达上限</div>
      </div>
      <template v-else>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </template>
    </template>
    <div v-else class="progress-box">
      <el-progress
        type="circle"
        :percentage="percentage"
        :status="null"
      ></el-progress>
    </div>
  </el-upload>
</template>

<script>
export default {
  props: {
    action: {
      type: String,
      required: true
    },
    fileType: {
      type: String,
      default() {
        return '*'
      }
    },
    fileList: {
      type: Array,
      default() {
        return []
      }
    },
    limit: {
      type: Number,
      default() {
        return 1
      }
    },
    listType: {
      type: String,
      default() {
        return 'picture'
      }
    },
    data: {
      type: Object,
      default() {
        return {}
      }
    },
    beforeUploadMethod: {
      type: Function,
      default() {
        return function() {}
      }
    }
  },
  data() {
    return {
      fileLoding: false,
      percentage: 0
    }
  },
  created() {},
  methods: {
    beforeUpload(file) {
      this.fileLoding = true
      this.$emit('beforeUpload', file)
      if (this.beforeUploadMethod) {
        return this.beforeUploadMethod(file)
      }
    },
    uploadSuccess(response, file, fileList) {
      this.fileLoding = false
      this.$emit('success', file, response, fileList)
    },
    uploadProgress(event, file, fileList) {
      this.fileLoding = true
      this.percentage = Number(event.percent.toFixed(2))
    },
    handleRemove(file, fileList) {
      this.fileLoding = false
      this.percentage = 0
      this.$emit('update:fileList', fileList)
    },
    uploadError() {
      Tip.warn('文件上传失败，请重试')
      this.fileLoding = false
      this.$emit('fail')
    }
  }
}
</script>
<style lang="less" scoped>
.progress-box {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.disabled {
  cursor: not-allowed;
}
</style>
